
#include <assert.h>
#include <malloc.h>
#include <sys/stat.h>

#include "c_TT_Font.h"

char wiigi::c_TT_Font::m_StringBuffer[ d_StringBufferSize ];
wchar_t wiigi::c_TT_Font::m_StringWBuffer[ d_StringBufferSize ];


/**
 * default contrsuctor
 */
wiigi::c_TT_Font::c_TT_Font( void )
:
   m_TTF_Buffer( 0 ),
   m_freeTypeGX( 0 ),
   m_Colour( ftgxWhite ),
   m_Style( FTGX_NULL ),
   m_StringBufferMutex( )
{
   
   return;
}

/**
 * destructor
 */
wiigi::c_TT_Font::~c_TT_Font( void )
{
   reset();
   
   return;
}

wiigi::e_Status wiigi::c_TT_Font::loadTTF( 
   const char* FileName,
   u32         PointSize,
   bool        CacheAll /*= false*/
   )
{
   e_Status Status;
   Status = d_StatusOK;
   
   FILE* fp;
   fp = 0;
   
   reset();
   
   struct stat FileStat;
   int RetCode;
   RetCode = stat( FileName, &FileStat );
   if( 0 != RetCode )
   {
      Status = d_Failed;
      goto Exit;
   }
   
   m_TTF_Buffer = new u8[ FileStat.st_size ];
   if( 0 == m_TTF_Buffer )
   {
      Status = d_StatusNoMemory;
      goto Exit;
   }
   
   fp = fopen( FileName, "rb" );
   if( 0 == fp )
   {
      Status = d_StatusBadFileName;
      goto Exit;
   }

   int Bytes;
   Bytes = fread( m_TTF_Buffer, 1, FileStat.st_size, fp );
   if( FileStat.st_size != Bytes )
   {
      Status = d_Failed;
      goto Exit;
   }

   m_freeTypeGX = new FreeTypeGX();
   if( 0 == m_freeTypeGX )
   {
      Status = d_StatusNoMemory;
      goto Exit;
   }

   m_freeTypeGX->loadFont( m_TTF_Buffer, Bytes, (FT_UInt)PointSize, CacheAll );

Exit:
   assert( d_StatusUnkown != Status );   
   
   if( 0 != fp )
   {
      fclose( fp );
      fp = 0;
   }
   
   if( d_StatusOK != Status )
   {
      reset();
   }

   return Status;
   
}


uint16_t wiigi::c_TT_Font::drawFixedText( 
   uint16_t x, 
   uint16_t y, 
   wchar_t const *text
)
{
   if( m_freeTypeGX )
   {
      m_freeTypeGX->drawText( 
         x, 
         y, 
         text, 
         m_Colour, 
         m_Style
      );
   }
   
   return 0; //@todo - what to report here????  
}

void wiigi::c_TT_Font::drawText( 
   uint16_t x, 
   uint16_t y, 
   const char * FormatMsg,
   ...
)
{
   c_Mutex::Locker Lock( m_StringBufferMutex );
     
   va_list ArgList;
   va_start(ArgList, FormatMsg);
   u32 Length = vsprintf( m_StringBuffer, FormatMsg, ArgList);
  
   u32 Idx;
   for( Idx = 0; Idx < Length; Idx++ )
   {
      m_StringWBuffer[ Idx ] = m_StringBuffer[ Idx ];
   }
   m_StringWBuffer[ Idx ] = 0;
   
   m_freeTypeGX->drawText( 
      x,
      y,
      m_StringWBuffer
   );
      
   return;
}
